//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package impl

import (
	"encoding/json"
	"fmt"
	net_url "net/url"
	"strings"

	"atomgit.com/openlinksaas-org/search-proxy/core"
	"github.com/dchest/uniuri"
)

type JuejinParser struct{}

type JuejinArticle struct {
	Title        string `json:"title"`
	BriefContent string `json:"brief_content"`
}

type JuejinResultModel struct {
	ArticleId   string        `json:"article_id"`
	ArticleInfo JuejinArticle `json:"article_info"`
}

type JuejinDataItem struct {
	ResultModel JuejinResultModel `json:"result_model"`
}

type JuejinResponse struct {
	Data []JuejinDataItem `json:"data"`
}

func (parser *JuejinParser) MatchUrl(url string) bool {
	return strings.HasPrefix(url, "https://juejin.cn/search")
}

func (parser *JuejinParser) Parse(url string) ([]*core.SearchEntry, error) {
	urlInfo, err := net_url.Parse(url)
	if err != nil {
		return nil, err
	}
	queryStr := urlInfo.Query().Get("query")

	newUrl := fmt.Sprintf("https://api.juejin.cn/search_api/v1/search?uuid=%s&query=%s", uniuri.NewLen(10), net_url.QueryEscape(queryStr))

	body, err := GetPage(newUrl)
	if err != nil {
		return nil, err
	}
	fmt.Println()
	resp := &JuejinResponse{}
	err = json.Unmarshal(body, resp)
	if err != nil {
		return nil, err
	}

	retList := []*core.SearchEntry{}
	for _, item := range resp.Data {
		if item.ResultModel.ArticleId == "" {
			continue
		}
		retList = append(retList, &core.SearchEntry{
			Title:   item.ResultModel.ArticleInfo.Title,
			Url:     fmt.Sprintf("https://juejin.cn/post/%s", item.ResultModel.ArticleId),
			Summary: item.ResultModel.ArticleInfo.BriefContent,
		})
	}
	return retList, nil
}
